import React, { useState } from "react";
import config from "../../../config/config";
import * as documentService from '../services/documentService';

export default function useDocumentState() {

    const [documentLoading, setDocumentLoading] = useState(false);
    const [currentPage, setCurrentPage] = useState(0);
    const [pageSize, setPageSize] = useState(config.defalut_page_size);
    const [documentTotal, setDocumentTotal] = useState(0);
    const [documentList, setDocumentList] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [searchParams, setSearchParams] = useState({});
    const [documentModalVisible, setDocumentModalVisible] = useState(false);
    const [documentType, setDocumentType] = useState("Document");
    const [uploadedDocumentFile, setUploadedDocumentFile] = useState(null);
    const [documentRecord, setDocumentRecord] = useState(null);
    const [previewModalVisible, setPreviewModalVisible] = useState(false);

    const onPreview = (record) => {
        setPreviewModalVisible(true);
        let params = { id: record.id, documentName: record.document_name, documentType: record.document_type };
        documentService.previewDocument(params).then(res => {
            if (res.code == 200) {
                record.document_content = res.data;
                setDocumentRecord(record);
            }
        });
    }

    const onDownload = (record) => {
        if ("html" == record.document_type) {
            window.open(record.document_name);
        } else {
            let params = { id: record.id, documentName: record.document_name };
            documentService.downloadDocument(params);
        }
    }

    const onDeleteDocument = (ids) => {
        let params = { ids: ids.join(","), current_page: "0", page_size: 10 };
        documentService.deleteDocument({ ...params, ...searchParams }).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setDocumentTotal(data.total);
                setDocumentList(data.records);
            }
        });
    }

    return {
        documentLoading, setDocumentLoading,
        currentPage, setCurrentPage,
        pageSize, setPageSize,
        documentTotal, setDocumentTotal,
        documentList, setDocumentList,
        selectedRowKeys, setSelectedRowKeys,
        selectedRows, setSelectedRows,
        searchParams, setSearchParams,
        documentModalVisible, setDocumentModalVisible,
        documentType, setDocumentType,
        uploadedDocumentFile, setUploadedDocumentFile,
        onPreview, documentRecord,
        previewModalVisible, setPreviewModalVisible,
        onDownload, onDeleteDocument
    };
}
